package com.navi.loaddata.loadhis;

import com.alibaba.fastjson.JSONObject;
import com.navi.loaddata.core.gpEntity.WppCdefectGlassF;
import com.navi.loaddata.core.mysqlEntity.QrtzEtlDetail;
import com.navi.loaddata.core.repository.impl.GreenPlumRepositoryImpl;
import com.navi.loaddata.core.repository.impl.MySqlRepositoryImpl;
import com.navi.loaddata.utils.JacksonUtil;
import com.navi.loaddata.utils.SaveEtlPoint;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Transactional(transactionManager = "secondaryPlatformTransactionManager")
public class LoadCT1His2 {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    JedisPool jedisPool;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private GreenPlumRepositoryImpl dao2;

    @Autowired
    private MySqlRepositoryImpl mysqlDao;

    @Autowired
    private SaveEtlPoint saveEtlPoint;


    //@Scheduled(fixedDelay = 3000)
    @Transactional(value = "secondaryPlatformTransactionManager")

    public void loadprodHis() {
        StringBuffer hqlBuffer = new StringBuffer("From QrtzEtlDetail WHERE projectName='").append("loaddata").append("'");
        hqlBuffer.append(" and schedName = '").append("LoadCT1His").append("'");
        hqlBuffer.append(" and instanceName = '").append("wpp_cdefect_glass_f").append("'");
        List<QrtzEtlDetail> qrtzEtlDetailList = mysqlDao.find(QrtzEtlDetail.class, hqlBuffer.toString());

        Timestamp startTime = qrtzEtlDetailList.get(0).getCheckinTime();
        Timestamp endTime = qrtzEtlDetailList.get(0).getEndTime();
        String relFlg = qrtzEtlDetailList.get(0).getRelFlg();
        Integer cnt = 0;

        if (endTime.getTime() <= new Date().getTime()-60000*7 && relFlg.equalsIgnoreCase("Y")){
            List<WppCdefectGlassF> ope4600AYList = dao2.list(WppCdefectGlassF.class, "From WppCdefectGlassF WHERE opeId='" + 4600 + "' and evtTimestamp<='" + Timestamp.valueOf(dateFormat.format(new Date(new Date().getTime()+60000*60*24*5))) + "' and dbTimestamp>='" + startTime + "' and dbTimestamp<='" + endTime + "' and realFlg='Y' and opeMode='AY'");
            List<WppCdefectGlassF> ope4600OYList = dao2.list(WppCdefectGlassF.class, "From WppCdefectGlassF WHERE opeId='" + 4600 + "' and evtTimestamp<='" + Timestamp.valueOf(dateFormat.format(new Date(new Date().getTime()+60000*60*24*5))) + "' and dbTimestamp>='" + startTime + "' and dbTimestamp<='" + endTime + "' and realFlg='Y' and opeMode='OY'");
            List<WppCdefectGlassF> ope4610List = dao2.list(WppCdefectGlassF.class, "From WppCdefectGlassF WHERE opeId='" + 4610 + "' and evtTimestamp<='" + Timestamp.valueOf(dateFormat.format(new Date(new Date().getTime()+60000*60*24*5))) + "' and dbTimestamp>='" + startTime + "' and dbTimestamp<='" + endTime + "' and realFlg='Y'");
            List<WppCdefectGlassF> ope4670List = dao2.list(WppCdefectGlassF.class, "From WppCdefectGlassF WHERE opeId='" + 4670 + "' and evtTimestamp<='" + Timestamp.valueOf(dateFormat.format(new Date(new Date().getTime()+60000*60*24*5))) + "' and dbTimestamp>='" + startTime + "' and dbTimestamp<='" + endTime + "' and realFlg='Y'");
            List<WppCdefectGlassF> dataList = new ArrayList<>();
            dataList.addAll(ope4600AYList);
            dataList.addAll(ope4600OYList);
            dataList.addAll(ope4610List);
            dataList.addAll(ope4670List);
            try (Jedis jedis = jedisPool.getResource()) {
                if (CollectionUtils.isNotEmpty(dataList)) {
                    for (WppCdefectGlassF data : dataList) {
                        WppCdefectGlassF dataTmp1 = new WppCdefectGlassF();
                        WppCdefectGlassF dataTmp2 = new WppCdefectGlassF();
                        BeanUtils.copyProperties(data, dataTmp1);
                        BeanUtils.copyProperties(data, dataTmp2);
                        dataTmp1.setDbTimestamp(null);
                        dataTmp2.setDbTimestamp(null);
                        if ("4670".equals(data.getOpeId())){
                            cnt = CT1FWork(jedis, dataTmp1, cnt);
                        }else {
                            cnt = CT1Work(jedis, dataTmp2, cnt);
                            cnt = CT1FWork(jedis, dataTmp1, cnt);
                        }
                    }
                }
                //System.out.println("[LoadCT1Log22]"+Timestamp.valueOf(dateFormat.format(new Date()))+"   写入数据:"+cnt+"   【dbStartTime:"+startTime+" -- "+"dbEndTime:"+endTime+"】");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public Integer CT1Work(Jedis jedis,WppCdefectGlassF data, Integer cnt){
        String key = String.format("C-Glass-CT1:%s:%s", "CT1", data.getGlassId());  // Value: evtTimestamp # resourceOpe
        String redisValue = jedis.get(key);
        long redisEvtTime = null==redisValue?0:Long.valueOf(redisValue.split("#")[0]).longValue();
        String resourceOpe = null==redisValue?null:redisValue.split("#")[1];
        String evtTimestamp = data.getEvtTimestamp().toString();
        long evtTimestamp2 = Long.valueOf(evtTimestamp.substring(0,4)+evtTimestamp.substring(5,7)+evtTimestamp.substring(8,10)
                +evtTimestamp.substring(11,13)+evtTimestamp.substring(14,16)+evtTimestamp.substring(17,19)).longValue();
        /**
         * N种情况: 1.首次记录。
         *         2.Redis中evt_timestamp < 此片玻璃的evt_timestamp
         *        3.Redis中evt_timestamp > 此片玻璃的evt_timestamp
         *       4.Redis中evt_timestamp = 此片玻璃的evt_timestamp
         **/
        if (redisValue == null || redisValue == "") {
            jedis.set(key, evtTimestamp2 + "#" + data.getOpeId());
            data.setSourceOpeId(data.getOpeId());
            data.setOpeId("CT1");
            data.setOpeKeyFk(151);
            String jsonString = JacksonUtil.toJSONStr(data);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            jsonObject.put("ope_tbl_name", "wpp_cdefect_glass_f");
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", jsonObject.toJSONString().getBytes());
            cnt += 1;
        }else if (redisEvtTime < evtTimestamp2 || (redisEvtTime == evtTimestamp2 && Integer.parseInt(data.getOpeId()) > Integer.parseInt(resourceOpe))){
            String redisEvtTime2 = String.valueOf(redisEvtTime).substring(0,4)+"-"+String.valueOf(redisEvtTime).substring(4,6)+"-"+String.valueOf(redisEvtTime).substring(6,8)+" "
                    +String.valueOf(redisEvtTime).substring(8,10)+":"+String.valueOf(redisEvtTime).substring(10,12)+":"+String.valueOf(redisEvtTime).substring(12,14);
            //String updateSql = "update wpp_cdefect_glass_f set real_flg = 'N', etl_timestamp = '"+ Timestamp.valueOf(dateFormat.format(new Date()))
            //        + "' where ope_id='CT1' and source_ope_id='"+ resourceOpe + "' and glass_id='" + data.getGlassId() +"' and evt_timestamp='"+ redisEvtTime2 + "'";
            JSONObject update_columns = new JSONObject();
            update_columns.put("real_flg", "N");
            update_columns.put("etl_timestamp", (Timestamp.valueOf(dateFormat.format(new Date())).toString()));

            JSONObject query_conditions = new JSONObject();
            query_conditions.put("ope_id", "CT1");
            query_conditions.put("source_ope_id", resourceOpe);
            query_conditions.put("glass_id", data.getGlassId());
            query_conditions.put("evt_timestamp", redisEvtTime2);

            JSONObject updateJsonObj = new JSONObject();
            updateJsonObj.put("update_flg", "true");
            updateJsonObj.put("ope_tbl_name", "wpp_cdefect_glass_f");
            updateJsonObj.put("query_conditions", query_conditions);
            updateJsonObj.put("update_columns", update_columns);

            jedis.set(key, evtTimestamp2 + "#" + data.getOpeId());
            data.setSourceOpeId(data.getOpeId());
            data.setOpeId("CT1");
            data.setOpeKeyFk(151);
            data.setRealFlg("Y");
            String jsonString = JacksonUtil.toJSONStr(data);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            jsonObject.put("ope_tbl_name", "wpp_cdefect_glass_f");
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", updateJsonObj.toJSONString().getBytes());
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", jsonObject.toJSONString().getBytes());
            cnt += 1;
        }else if (redisEvtTime == evtTimestamp2 && Integer.parseInt(data.getOpeId()) == Integer.parseInt(resourceOpe)) {
            data.setSourceOpeId(data.getOpeId());
            data.setOpeId("CT1");
            data.setOpeKeyFk(151);
            data.setRealFlg("Y");
            String jsonString = JacksonUtil.toJSONStr(data);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            jsonObject.put("ope_tbl_name", "wpp_cdefect_glass_f");
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", jsonObject.toJSONString().getBytes());
            cnt += 1;
        }
        return cnt;
    }

    public Integer CT1FWork(Jedis jedis,WppCdefectGlassF data, Integer cnt){
        String key = String.format("C-Glass-CT1:%s:%s", "CT1F", data.getGlassId());  // Value: evtTimestamp # resourceOpe
        String redisValue = jedis.get(key);
        long redisEvtTime = null==redisValue?0:Long.valueOf(redisValue.split("#")[0]).longValue();
        String resourceOpe = null==redisValue?null:redisValue.split("#")[1];
        String evtTimestamp = data.getEvtTimestamp().toString();
        long evtTimestamp2 = Long.valueOf(evtTimestamp.substring(0,4)+evtTimestamp.substring(5,7)+evtTimestamp.substring(8,10)
                +evtTimestamp.substring(11,13)+evtTimestamp.substring(14,16)+evtTimestamp.substring(17,19)).longValue();
        /**
         * N种情况: 1.首次记录。
         *         2.Redis中evt_timestamp < 此片玻璃的evt_timestamp
         *        3.Redis中evt_timestamp > 此片玻璃的evt_timestamp
         *       4.Redis中evt_timestamp = 此片玻璃的evt_timestamp
         **/
        if (redisValue == null || redisValue == "") {
            jedis.set(key, evtTimestamp2 + "#" + data.getOpeId());
            data.setSourceOpeId(data.getOpeId());
            data.setOpeId("CT1F");
            data.setOpeKeyFk(152);
            String jsonString = JacksonUtil.toJSONStr(data);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            jsonObject.put("ope_tbl_name", "wpp_cdefect_glass_f");
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", jsonObject.toJSONString().getBytes());
            cnt += 1;
        }else if (redisEvtTime < evtTimestamp2 || (redisEvtTime == evtTimestamp2 && Integer.parseInt(data.getOpeId()) > Integer.parseInt(resourceOpe))){
            String redisEvtTime2 = String.valueOf(redisEvtTime).substring(0,4)+"-"+String.valueOf(redisEvtTime).substring(4,6)+"-"+String.valueOf(redisEvtTime).substring(6,8)+" "
                    +String.valueOf(redisEvtTime).substring(8,10)+":"+String.valueOf(redisEvtTime).substring(10,12)+":"+String.valueOf(redisEvtTime).substring(12,14);
            //String updateSql = "update wpp_cdefect_glass_f set real_flg = 'N', etl_timestamp = '"+ Timestamp.valueOf(dateFormat.format(new Date()))
            //        + "' where ope_id='CT1F' and source_ope_id='"+ resourceOpe + "' and glass_id='" + data.getGlassId() +"' and evt_timestamp='"+ redisEvtTime2 + "'";
            JSONObject update_columns = new JSONObject();
            update_columns.put("real_flg", "N");
            update_columns.put("etl_timestamp", (Timestamp.valueOf(dateFormat.format(new Date())).toString()));

            JSONObject query_conditions = new JSONObject();
            query_conditions.put("ope_id", "CT1F");
            query_conditions.put("source_ope_id", resourceOpe);
            query_conditions.put("glass_id", data.getGlassId());
            query_conditions.put("evt_timestamp", redisEvtTime2);

            JSONObject updateJsonObj = new JSONObject();
            updateJsonObj.put("update_flg", "true");
            updateJsonObj.put("ope_tbl_name", "wpp_cdefect_glass_f");
            updateJsonObj.put("query_conditions", query_conditions);
            updateJsonObj.put("update_columns", update_columns);

            jedis.set(key, evtTimestamp2 + "#" + data.getOpeId());
            data.setSourceOpeId(data.getOpeId());
            data.setOpeId("CT1F");
            data.setOpeKeyFk(152);
            data.setRealFlg("Y");
            String jsonString = JacksonUtil.toJSONStr(data);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            jsonObject.put("ope_tbl_name", "wpp_cdefect_glass_f");
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", updateJsonObj.toJSONString().getBytes());
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", jsonObject.toJSONString().getBytes());
            cnt += 1;
        }else if (redisEvtTime == evtTimestamp2 && Integer.parseInt(data.getOpeId()) == Integer.parseInt(resourceOpe)){
            data.setSourceOpeId(data.getOpeId());
            data.setOpeId("CT1F");
            data.setOpeKeyFk(152);
            data.setRealFlg("Y");
            String jsonString = JacksonUtil.toJSONStr(data);
            JSONObject jsonObject = JSONObject.parseObject(jsonString);
            jsonObject.put("ope_tbl_name", "wpp_cdefect_glass_f");
            rabbitTemplate.convertAndSend("qmsExchange", "C_GLASS", jsonObject.toJSONString().getBytes());
            cnt += 1;
        }
        return cnt;
    }
}
